import { FC, useEffect, useState, ReactElement, useCallback } from 'react'
import { Button, Table, message, Progress, Form, Select, Radio } from 'antd'
import {
  connect,
  AccountModelState,
  Dispatch,
  Location,
  DistributeInfoType
} from 'umi'
import type { ColumnsType } from 'antd/es/table'
import type { RadioChangeEvent } from 'antd'
import produce from 'immer'
import { onlyKey, excelDownload } from '@/utils'
import DistributionPage from './components/distribution'
import ChooseExpert from './components/choose-expert'
import styles from './index.less'
const { Option } = Select
interface IProps {
  dispatch: Dispatch
  accountModel: AccountModelState
  location: Location
}

const AccountPage: FC<IProps> = ({
  dispatch,
  accountModel,
  location
}): ReactElement => {
  const { batchCode } = location.query as { batchCode: string }
  const { scoreType, gradeInfo, distributeInfo } = accountModel
  const [distributionVisible, setDistributionVisible] = useState<boolean>(false)
  const [showExpert, setShowExpert] = useState<boolean>(false)
  const [grade, setGrade] = useState<string>('')
  const [modalPayload, setModalPayload] = useState<any>({})
  const [expandData, setExpandData] = useState<any>({})
  const [dataSource, setDataSource] = useState<DistributeInfoType[]>([])
  const [expandedRowKeys, setexpandedRowKeys] = useState<string[]>([])

  //   选择评审类型
  const handleType = (e: RadioChangeEvent, questionCode: string) => {
    setDataSource(
      produce((draft) => {
        draft.forEach((item: DistributeInfoType) => {
          if (item.questionCode === questionCode) {
            item.type = e.target.value
          }
        })
      })
    )
  }

  const columns: ColumnsType<DistributeInfoType> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (text: string, record: any, index: number) => {
        return <span>{(index + 1).toString()?.padStart(2, '0')}</span>
      },
      align: 'center'
    },
    {
      title: '指标名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center'
    },
    {
      title: '评审方式',
      dataIndex: 'type',
      key: 'type',
      render: (text: string, record: DistributeInfoType, index: number) => {
        return (
          <Radio.Group
            onChange={(e) => handleType(e, record.questionCode)}
            value={record.type}
          >
            {scoreType.map((item) => (
              <Radio value={item.dictValue} key={item.dictKey}>
                {item.dictValue}
              </Radio>
            ))}
          </Radio.Group>
        )
      }
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: ' operation',
      align: 'center',
      render: (text: string, record: any) => {
        return (
          <span
            onClick={() => chooseExpert(record)}
            className={styles['choose-expert']}
          >
            选择专家
          </span>
        )
      }
    }
  ]

  const handleUpdate = () => {
    getDistributeInfo(grade)
  }

  const expandedRowRender = (item: DistributeInfoType) => {
    const columns: any[] = [
      {
        title: '教师名称',
        dataIndex: 'reviewerName',
        key: 'reviewerName',
        align: 'center'
      },
      {
        title: '密码',
        dataIndex: 'passWord',
        key: 'passWord',
        align: 'center'
      },
      {
        title: '分配数量',
        key: 'total',
        dataIndex: 'total',
        align: 'center'
      },
      {
        title: '已评数量',
        dataIndex: 'finish',
        key: 'finish',
        align: 'center'
      },
      {
        title: '进度',
        dataIndex: 'progress',
        key: 'progress',
        align: 'center',
        render: (text: string, record: any, index: number) => {
          return (
            <>
              <Progress
                percent={
                  Math.round((record.finish / record.total) * 10000) / 100
                }
              ></Progress>
            </>
          )
        }
      }
    ]

    return (
      <Table
        columns={columns}
        dataSource={expandData[item.order]}
        pagination={false}
      />
    )
  }

  //   查询评分方式
  const getScoringType = useCallback(() => {
    dispatch({
      type: 'accountModel/function_getScoringType',
      payload: {}
    })
  }, [])

  const getDistributeInfo = (grade: string) => {
    dispatch({
      type: 'accountModel/function_getDistributeInfo',
      payload: {
        batchCode,
        grade
      }
    })
  }

  // 账号分配
  const distribute = useCallback(() => {
    setDistributionVisible(true)
  }, [])

  const modalHide = useCallback(() => {
    setDistributionVisible(false)
    getDistributeInfo(grade)
  }, [grade])

  const downloadAccount = useCallback(() => {
    dispatch({
      type: 'accountModel/function_downloadReviewerInfo',
      payload: {
        batchCode
      },
      callback: (response) => {
        excelDownload(response, '账号列表.xlsx')
        message.success('下载成功')
      }
    })
  }, [])

  // 批次学段信息
  const getBatchGradeInfo = () => {
    dispatch({
      type: 'accountModel/function_getBatchGradeInfo',
      payload: {
        batchCode
      }
    })
  }

  const chooseExpert = (record: any) => {
    setModalPayload({
      batchCode,
      grade,
      questionCode: record.questionCode,
      type: scoreType.find((item) => item.dictValue === record.type)?.dictKey,
      selectedExpert: record.child
    })
    setShowExpert(true)
  }

  const onchange = (e: string) => {
    setGrade(e)
    getDistributeInfo(e)
  }

  const openClick = (status: boolean, item: DistributeInfoType) => {
    const { order } = item
    if (!status) {
      setexpandedRowKeys((prev) => prev.filter((item) => item != order))
      return
    } else {
      setexpandedRowKeys((prev) => [...prev, order])
    }

    setExpandData({
      ...expandData,
      [item.order]:
        item.child.map((item) => ({
          key: onlyKey(),
          ...item
        })) ?? []
    })
  }

  useEffect(() => {
    getBatchGradeInfo()
    getScoringType()
  }, [])

  useEffect(() => {
    if (gradeInfo.length) {
      setGrade(gradeInfo[0].code)
      getDistributeInfo(gradeInfo[0].code)
    }
  }, [gradeInfo])

  useEffect(() => {
    if (distributeInfo.length) {
      const temp: any[] = JSON.parse(JSON.stringify(distributeInfo))
      temp.forEach((item, index) => {
        item.child = item.children ?? []
        delete item.children
        if (index === 0) {
          setExpandData({
            [item.order]: item.child.map((item: any) => ({
              key: onlyKey(),
              ...item
            }))
          })
          setexpandedRowKeys([item.order])
        }
      })
      setDataSource(temp)
    }
  }, [distributeInfo])

  return (
    <>
      <div className={styles['page-wrapper']}>
        <div className={styles['account-pannel']}>
          <div className={styles['pannel-title']}>
            <span className={styles.title}>账号分配结果</span>
            <div className={styles['btn-wrappper']}>
              <Button
                type="primary"
                onClick={() => distribute()}
                style={{ marginRight: '24px' }}
              >
                专家账号生成
              </Button>
              <Button
                type="primary"
                className="set-btn"
                onClick={downloadAccount}
              >
                下载账号
              </Button>
            </div>
          </div>
          <div className={styles['pannel-content']}>
            <div className={styles['form-wrapper']}>
              <Form>
                <Form.Item label="学段">
                  <Select
                    placeholder="请选择学段"
                    style={{ width: '200px' }}
                    value={grade}
                    onChange={onchange}
                  >
                    {gradeInfo.map((item) => (
                      <Option value={item.code} key={item.code}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Form>
            </div>
            <Table
              dataSource={dataSource}
              columns={columns}
              rowKey="order"
              expandable={{
                expandedRowRender,
                expandedRowKeys: expandedRowKeys
              }}
              pagination={false}
              onExpand={openClick}
            />
          </div>
        </div>

        {/* 账号分配设置 */}
        <DistributionPage
          visible={distributionVisible}
          hide={modalHide}
          location={location}
        />

        {/* 选择专家 */}
        <ChooseExpert
          visible={showExpert}
          hide={() => setShowExpert(false)}
          payload={modalPayload}
          update={() => handleUpdate()}
        />
      </div>
    </>
  )
}

const mapStateToProps = ({
  accountModel
}: {
  accountModel: AccountModelState
}) => {
  return {
    accountModel
  }
}

export default connect(mapStateToProps)(AccountPage)
